from datetime import datetime
from app.extensions import db

class Problem(db.Model):
    __tablename__ = 'problems'

    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
    title = db.Column(db.String(100), nullable=False)
    difficulty = db.Column(db.Enum('easy', 'medium', 'hard', name='problem_difficulty'), nullable=False)
    requirement = db.Column(db.Text, nullable=False)
    content = db.Column(db.Text, nullable=False)
    creator_id = db.Column(db.BigInteger, db.ForeignKey('users.id'), nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    update_time = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)

    solutions = db.relationship('Solution', backref='problem', lazy=True)
    likes = db.relationship('ProblemLike', backref='problem', lazy=True)
    
    def to_dict(self):
        return {
            'id': self.id,
            'title': self.title,
            'difficulty': self.difficulty,
            'requirement': self.requirement,
            'content': self.content,
            'creator_id': self.creator_id,
            'create_time': self.create_time.isoformat(),
            'update_time': self.update_time.isoformat()
        }
        
    def save(self):
        try:
            db.session.add(self)
            db.session.commit()
            return True
        except Exception as e:
            db.session.rollback()
            return False
            
    def delete(self):
        try:
            db.session.delete(self)
            db.session.commit()
            return True
        except Exception as e:
            db.session.rollback()
            return False


class Solution(db.Model):
    __tablename__ = 'solutions'

    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
    problem_id = db.Column(db.BigInteger, db.ForeignKey('problems.id'), nullable=False)
    author_id = db.Column(db.BigInteger, db.ForeignKey('users.id'), nullable=False)
    language = db.Column(db.String(20), nullable=False)
    content = db.Column(db.Text, nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    update_time = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)

class ProblemLike(db.Model):
    __tablename__ = 'problem_likes'

    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
    problem_id = db.Column(db.BigInteger, db.ForeignKey('problems.id'), nullable=False)
    user_id = db.Column(db.BigInteger, db.ForeignKey('users.id'), nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)

    __table_args__ = (
        db.UniqueConstraint('problem_id', 'user_id', name='uk_problem_user'),
    )